import { defineStore } from "pinia";
import { setToken, removeToken } from "@/utils";
import { Base64 } from "js-base64";
import { login } from "@/data-services/api";
import router from "@/vue-router";

import { PERMISSION_READONLY, USER_ROLE_TOURIST } from "./constants";

interface T_User_Config {
  permission: number;
  role: string | number;
  userName: string;
  isLogout: boolean;
}

function getUserInfoLocal() {
  const userInfo = sessionStorage.getItem("sedcLXSHaiUserInfo");
  if (userInfo) {
    return JSON.parse(userInfo);
  }
  return {
    userName: "",
  };
}
const userConfigStore = defineStore("userConfigStore", {
  state(): T_User_Config {
    const initUserInfo = getUserInfoLocal();
    return {
      role: USER_ROLE_TOURIST,
      permission: PERMISSION_READONLY,
      userName: "",
      isLogout: false,
      ...initUserInfo,
    };
  },
  getters: {
    hasLoggedIn(state) {
      return !!state.userName && !state.isLogout;
    },
  },
  actions: {
    login(options: {
      userName: string;
      passWord: string;
      remmemberMe: boolean;
    }): Promise<void> {
      const { remmemberMe, userName, passWord } = options;

      let params = {
        name: userName,
        password: passWord,
      };

      return login(params).then((response) => {
        const res = response.data;
        const { privilege, name, auth_token, permission } = res;
        setToken(auth_token);
        this.role = privilege;
        this.userName = name;
        this.permission = permission;
        this.isLogout = false;
        this.saveUserInfoLocal({
          role: privilege,
          userName: name,
          permission,
          isLogout: false,
        });
        if (remmemberMe) {
          localStorage.setItem("SEDC_DATA_UserName", userName);
          localStorage.setItem("SEDC_DATA_PassWord", Base64.encode(passWord));
        } else {
          localStorage.removeItem("SEDC_DATA_UserName");
          localStorage.removeItem("SEDC_DATA_PassWord");
        }
      });
    },
    logOut(): void {
      removeToken();
      this.isLogout = true;
      this.permission = PERMISSION_READONLY;
      this.role = USER_ROLE_TOURIST;
      sessionStorage.removeItem("sedcLXSHaiUserInfo");
      router.replace({ path: "/login" });
    },
    saveUserInfoLocal(info: any) {
      const userInfo = JSON.stringify(info);
      sessionStorage.setItem("sedcLXSHaiUserInfo", userInfo);
    },
  },
});

export const userConfig = userConfigStore;
